<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区-->
    <el-card  class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList" >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 添加用户的对话框表单 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible" width="600px" @close="addDialogClosed" >
      <el-form  ref="addFormRef" :rules="addFormRules"   :model="form">
        <el-form-item label="用户名" :label-width="100+'px'" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="100+'px'" prop="password">
          <el-input v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="100+'px'" prop="Email">
          <el-input v-model="form.Email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="100+'px'" prop="tel">
          <el-input v-model="form.tel" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="dialogUpdateFormVisible" width="600px" @close="updateDialogClosed" >
      <el-form  ref="updateFormRef" :rules="addFormRules"   :model="updateForm">
        <el-form-item label="用户名" :label-width="100+'px'" prop="name">
          <el-input v-model="updateForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码"  :label-width="100+'px'" prop="password">
          <el-input v-model="updateForm.password" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="100+'px'" prop="Email">
          <el-input v-model="updateForm.Email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="100+'px'" prop="tel">
          <el-input v-model="updateForm.tel" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button  @click="dialogUpdateFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 是否删除用户弹框-->

      <!--用户列表表格-->
      <el-table :data="userList" style="width:100%" border stripe>
        <el-table-column label="序号" type="index" width="80"></el-table-column>
        <el-table-column label="用户名" prop="UserName" width="150"></el-table-column>
        <el-table-column label="手机"   prop="Mobile" width="200"></el-table-column>
        <el-table-column label="邮箱"   prop="Email" width="200"></el-table-column>
        <el-table-column label="角色"   prop="RoleName" width="120"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.MgState" active-color="#13ce66" inactive-color="#ddd" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="updateFormDialog(scope.row)"  >修改</el-button>
            <el-button type="danger" size="mini" @click="delUser(scope.row.id)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    //自定义验证邮箱规则
    var checkEmail=(rule, value, callback)=>{
      const regEmail=/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if(regEmail.test(value)){ //合法的邮箱地址
          callback()
      }else{
          callback(new Error('请输入合法的邮箱地址！'))
      }
    };
    var checkTel=(rule,value,callback)=>{
      const regTel=/^1[3456789]\d{9}$/
      if(regTel.test(value)){ 
        callback()
      }else{
        callback(new Error('请输入合法手机号！'))
      }
    };
    return {
      queryInfo: { query: '', pagenum: 1, pagesize: 5 },
      userList: [],
      total: 0,
      dialogFormVisible: false,
      dialogUpdateFormVisible:false,
      form: {
          name: '',
          password:'',
          Email:'',
          tel:''
        },
      updateForm: {
          name: '',
          password:'',
          Email:'',
          tel:''
        },
      addFormRules:{
          name: 
              [
                {required:true,message:'请输入用户名',trigger:'blur'},
                {min:3,max:10,message:'长度在3到 10 个字符',trigger:'blur'}
              ],
          password: 
              [
                {required:true,message:'请输入密码',trigger:'blur' },
                {min:6,max:15,message:'长度在 6 到 15 个字符',trigger:'blur'}
              ],
          Email: 
              [
                {required:true,message:'请输入邮箱',trigger:'blur' },
                {validator:checkEmail,trigger:'blur'}
              ],
          tel: 
              [
                {required:true,message:'请输入电话号码',trigger:'blur' },
                {validator:checkTel,trigger:'blur'}
              ]
        }  
    }
  },
  methods: {
    async getUserList() {
      var res = await this.$http.get('/api/users',{params: this.queryInfo}).then(res=>{
        this.userList = res.data.data
        this.total = res.data.total
      },err=>{
          console.log(err);
      })
    },
    //监听pagesize改变的事件
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList();
    },
    //监听PageNume改变的事件
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage
      this.getUserList();
    },
    //switch状态发生变化时的回调函数
    async userStateChanged(userinfo){
            const res=await this.$http.get('/api/userupdate',{params:userinfo})
            if(res.data.count<=0) return
            this.$message.success(res.data.count+'个状态信息已经修改成功！目前状态的值为：'+res.data.newState)
            console.log(res.data);
      //真实环境中修改数据的接口写法
      // const d=await this.$http.put('user',userinfo);
      // if(d<=0) return
      // this.$message.success('修改用户状态成功');
      },
    //监听添加用户的对话框的关闭事件
    addDialogClosed(){
      this.$refs.addFormRef.resetFields();
    },
    //添加用户
    addUser(){
      //向form中添加一些属性
      var query='query';
      var queryVal=this.queryInfo.query;
      this.form[query]=queryVal;

      var pagenum='pagenum';
      var pagenumVal=this.queryInfo.pagenum;
      this.form[pagenum]=pagenumVal;

      var pagesize='pagesize';
      var pagesizeVal=this.queryInfo.pagesize;
      this.form[pagesize]=pagesizeVal;

      this.$refs.addFormRef.validate(async valid=>{
        if(valid){
          const res=await this.$http.get('/api/adduser',{params:this.form});
          //真实环境中添加用户接口的写法
          // const d=await this.$http.post('/api/adduser',this.form);
          // if(d<=0) return 
          // this.$message.success('添加用户成功！');
          this.userList=res.data.data;
          this.total=res.data.total;
          this.dialogFormVisible=false;
        }
      });
    },
    //将当前表格中的数据复制到对话框中
    updateFormDialog(userInfo){
      this.dialogUpdateFormVisible=true;
      console.log(userInfo);
      this.updateForm.id=userInfo.id;
      this.updateForm.name=userInfo.UserName;
       this.updateForm.password=userInfo.Password;
      this.updateForm.Email=userInfo.Email;
      this.updateForm.tel=userInfo.Mobile;
    },
    //监听对话框关闭
    updateDialogClosed(){
      this.$refs.updateFormRef.resetFields();
    },
    //修改对话框中的数据
    updateUser(){
      var query='query';
      var queryVal=this.queryInfo.query;
      this.updateForm[query]=queryVal;

      var pagenum='pagenum';
      var pagenumVal=this.queryInfo.pagenum;
      this.updateForm[pagenum]=pagenumVal;

      var pagesize='pagesize';
      var pagesizeVal=this.queryInfo.pagesize;
      this.updateForm[pagesize]=pagesizeVal;

      this.$refs.updateFormRef.validate(async valid=>{
        if(valid){
          const res=await this.$http.get('/api/updateUser',{params:this.updateForm});
          //真实环境中添加用户接口的写法
          // const d=await this.$http.post('/api/adduser',this.form);
          // if(d<=0) return 
          // this.$message.success('添加用户成功！');
          this.userList=res.data.data;
          this.total=res.data.total;
          this.dialogUpdateFormVisible=false;
        }
      });
    },
   async delUser(id){
      var idInt='id';
      var idVal=id;
      this.queryInfo[idInt]=idVal;

      var res=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err)=>{
        return err;
      });
      if(res!='confirm') return this.$message.info('删除用户已取消');
      var removeuser=await this.$http.get('/api/deluser',{params:this.queryInfo});
      this.$message.info('删除用户成功')
      this.userList=removeuser.data.data;
      this.total=removeuser.data.total;
    }
  },
  created() {
    this.getUserList();
  }
}
</script>

<style lang="stylus" scoped>
  .el-table 
    margin-top 20px

  .box-card
    margin-top 30px

  .el-pagination
    margin-top 20px
    text-align center
  el-dialog
    display flex
    flex-direction column
    align-items center
    el-form
      margin 0px auto
  .dialog-footer
      text-align center
</style>